import {CheckOutlined, InboxOutlined, UndoOutlined} from '@ant-design/icons';
import {
  Modal,
  message,
  Form,
  Space,
  DatePicker,
  Upload,
  UploadProps,
  Row,
  Col,
  Input,
  Popconfirm,
  Select,
  Progress,
  TreeSelect, Button,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import MultiImgUpload from '@/components/multiImgUpload';
import '@/assets/css/index.less';
import ProForm, { ProFormText, ProFormSelect } from '@ant-design/pro-form';
import { useForm } from 'antd/es/form/Form';
import { getPhotoCategoryList, releasePhoto, uploadList } from '@/services/pictureManager';
import axios from 'axios';
import formatDate from '@/utils/formatDate';
import { UploadFile } from 'antd/lib/upload';
import { useLocation } from 'umi';
import {useModel} from "@@/plugin-model/useModel";
import {BASE_URL} from "../../../../proxyConfig";

const MNTPrefix = BASE_URL;
const { Dragger } = Upload;
const { TextArea } = Input;
const generatTreeData = (data) => {
  data.map((item, index) => {
    data[index].value = item.id;
    data[index].title = item.name;
    if (item.children && item.children.length > 0) {
      generatTreeData(item.children);
    }
  });
  return data;
};
const PicturenPublish: React.FC = () => {
  const location = useLocation();
  const [form] = useForm();
  const [categoryTreeData, setCategoryTreeData] = useState([]);
  const [currentFormValues, setCurrentFormValues] = useState(location.state?.formValues);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [fileResponse, setResponse] = useState([]);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const values = Form.useWatch([], form);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};


  const onSubmit = async () => {
    if (fileResponse.length === 0) {
      message.error('图片为空，请上传图片！');
      return;
    }
    // let fileListArray = [];
    // fileResponse.map(item => {
    //     fileListArray.push(item);
    // })
    const date = new Date();

    const tmp = {
      author:currentUser.name,
      ...values,
      photoCategoryId:"ec5b4ad0-0a41-4c7f-9983-6c24b7d08a4a",
      fileList: fileResponse,
      releaseTime:
        date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + '00:00:00',
    };
    if (currentFormValues === undefined) {
      const res = await releasePhoto(tmp);
      if (res.code == 0) {
        message.success('上传成功');
        window.location.href = window.location.href.replace(/imagePublish/, 'imageCenter');
      } else {
        message.info(res.data);
      }
    } else {
      //需要增加一个updatePhoto功能
    }
  };

  const handlePreview = async (file) => {
    setPreviewImage(MNTPrefix + file.response.data.data[0].src);
    setPreviewOpen(true);
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
  };
  const handleCancel = () => setPreviewOpen(false);

  const [progress, setProgress] = useState(0);
  const formLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 14,
    },
  };
  const validateUpload = (rule, values, callback) => {
    const len = fileList.length;
    if (len > 0) {
      console.log(values);
      callback();
    } else {
      callback('请上传图片');
    }
  };

  return (
    <PageContainer>
      <ProForm
        form={form}
        layout="horizontal"
        {...formLayout}
        initialValues={currentFormValues || {}}
        onFinish={() => onSubmit()}
        // onReset={onReset}
        submitter={{
          render: (_, dom) => (
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Space>
                {/*{dom}*/}
                {<Button onClick={() => {
                  _.reset()
                }}><UndoOutlined />重置</Button>}
                {<Button type={"primary"} onClick={() => {
                  _.submit()
                }}><CheckOutlined />提交</Button>}

              </Space>
            </div>
          ),
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '主题名称必填',
            },
          ]}
          width="md"
          name="theme"
          placeholder="请填写主题名称"
          label="主题名称"
        />
        <Form.Item label="说明" name="description">
          <TextArea
            className=""
            showCount
            maxLength={300}
            // style={{ height: 120, marginBottom: 24, width: 300}}
            // onChange={onChange}
            placeholder="输入备注信息"
          />
        </Form.Item>

{/*        <ProFormText
          rules={[
            {
              required: true,
              message: '发布作者必填',
            },
          ]}
          width="md"
          name="author"
          placeholder="请填写发布作者"
          label="发布作者"
        />*/}
        <ProFormText
          rules={[
            {
              required: true,
              message: '信息来源必填',
            },
          ]}
          width="md"
          name="source"
          placeholder="请填写信息来源"
          label="信息来源"
        />

        <Form.Item
          label="上传图片"
          name="fileList"
          rules={[
            {
              required: true,
              message: '请上传图片',
              validator: validateUpload,
            },
          ]}
        >
          <MultiImgUpload
            form={form}
            fileList={fileList}
            setFileList={setFileList}
            url={'/api/v1/photo/uploadList'}
            fileResponse={fileResponse}
            setResponse={setResponse}
          />
        </Form.Item>
        <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
          <img
            alt="example"
            style={{
              width: '100%',
            }}
            src={previewImage}
          />
        </Modal>
      </ProForm>
    </PageContainer>
  );
};
export default PicturenPublish;
